package com.example.demo.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.R;
import com.example.demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override // 在目标运行前运行，true放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求url
        String url = request.getRequestURL().toString();
        //login和register放行
        if(url.contains("login") || url.contains("register")){
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        log.info(request.getHeader("token"));
        //判断令牌是否存在
        if(!StringUtils.hasLength(token)){
            log.info("token 为空");
            String notLogin = JSONObject.toJSONString(R.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
            return false;
        }
        //解析token，失败返回未登录
        try{
            JWTUtils.getClaimsByToken(token);
        }catch (Exception e){
            String notLogin = JSONObject.toJSONString(R.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
            return false;
        }

        return true;
    }

}
